

#import "MailListXMLReader.h"
#import "IDominoAppDelegate.h"
static NSUInteger parsedMailEntriesCounter;

@implementation MailListXMLReader

@synthesize currentMailObject = _currentMailObject;
@synthesize currentColumnNumber=_currentColumnNumber;
@synthesize contentOfCurrentMailProperty=_contentOfCurrentMailProperty;
@synthesize mailCount;

- (void)parserDidStartDocument:(NSXMLParser *)parser
{
	IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
	_maxMailCount=[appDelegate defaultMaxMailCount];
	parsedMailEntriesCounter=0;
}

- (NSArray* )parseXMLFileFromData:(NSData *)data parseError:(NSError **)error
{	
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [parser setDelegate:self];
    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
	IDominoAppDelegate *appDelegate = (IDominoAppDelegate *)[[UIApplication sharedApplication] delegate];
    localMailDict=appDelegate.localMailDict;
	mailList=[[NSMutableArray alloc] init];
    [parser parse];
    
    NSError *parseError = [parser parserError];
    if (parseError && error) {
        *error = parseError;
    }
    [parser release];
	return [mailList autorelease];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if (qName) {
        elementName = qName;
    }  
    if ([elementName isEqualToString:@"viewentries"]) {
		NSNumber* topLevelEntries = [attributeDict valueForKey:@"toplevelentries"];
		if(topLevelEntries==0)
			[parser abortParsing];
		mailCount=[topLevelEntries intValue];
		return;
	}
	if ([elementName isEqualToString:@"viewentry"]) {		
        parsedMailEntriesCounter++;
		if (parsedMailEntriesCounter > _maxMailCount) {
			[parser abortParsing];
			return;
		}		
        // create an instance of it.
        self.currentMailObject = [[Mail alloc] init];
		[self.currentMailObject setUNID:[attributeDict valueForKey:@"unid"]];
        // Add the new Mail object to the application's array of mails.
		Mail* mail=[localMailDict objectForKey:[ self.currentMailObject UNID]];
		if(mail!=nil){
			[mailList addObject:mail];
		}
		else{
			[mailList addObject: self.currentMailObject];
			[localMailDict setObject: self.currentMailObject forKey:[ self.currentMailObject UNID]];
		}
		return;
    }
        
    if ([elementName isEqualToString:@"entrydata"]) {
        self.currentColumnNumber = [attributeDict valueForKey:@"columnnumber"];
		
    } else if ([elementName isEqualToString:@"text"]  || [elementName isEqualToString:@"number"] || [elementName isEqualToString:@"datetime"]) {
		self.contentOfCurrentMailProperty = [NSMutableString stringWithCapacity:30];
    } 
	else {
        self.contentOfCurrentMailProperty=nil;
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{     
    if (qName) {
        elementName = qName;
    }
	if ([elementName isEqualToString:@"viewentry"]) {
		[self.currentMailObject release];
	}
    if ([elementName isEqualToString:@"text"]) {
		if ([self.currentColumnNumber  isEqualToString:@"2"]) {
			self.currentMailObject.sender=self.contentOfCurrentMailProperty;
		}
		if ([self.currentColumnNumber isEqualToString:@"3"]) {
			self.currentMailObject.subject=self.contentOfCurrentMailProperty;
		}
    } else if ([elementName isEqualToString:@"number"]) {
		if ([self.currentColumnNumber isEqualToString:@"5"]) {
			NSString* newSize=self.contentOfCurrentMailProperty;
			while([newSize hasSuffix:@"\n"]){
				newSize=[newSize substringToIndex:[newSize length]-1];
			}
			self.currentMailObject.size=newSize;
		}
		else if([self.currentColumnNumber isEqualToString:@"6"]) {
			if([self.contentOfCurrentMailProperty isEqualToString:@"5"])
				[self.currentMailObject setHasAttachment:YES];
			else
				[self.currentMailObject setHasAttachment:NO];
		}
        
    } else if ([elementName isEqualToString:@"datetime"]) {
		if ([self.currentColumnNumber isEqualToString:@"4"]) {
			NSMutableString *mailDateString=[[NSMutableString alloc] init];
			[mailDateString setString:self.contentOfCurrentMailProperty];
			[mailDateString  insertString:@"-" atIndex:4];
			[mailDateString  insertString:@"-" atIndex:7];
			NSRange range={10,1};
			[mailDateString	replaceCharactersInRange:range withString:@" "];
			[mailDateString  insertString:@":" atIndex:13];
			[mailDateString  insertString:@":" atIndex:16];
			NSString* timezone1=[NSString stringWithFormat:@"%@", [mailDateString substringFromIndex:22]];
			if(timezone1.length==3){
				self.currentMailObject.date=[[NSDate alloc] initWithString:[NSString stringWithFormat:@"%@ +0800", [mailDateString substringToIndex:19]] ];
			}
			else
				self.currentMailObject.date=[[NSDate alloc] initWithString: [NSString stringWithFormat:@"%@ %@", [mailDateString substringToIndex:19], timezone1] ];//2008?08?08?10:01:53,42+10    YYYY-MM-DD HH:MM:SS ±HHMM
			[mailDateString release];
		}
		else {
		}
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (self.contentOfCurrentMailProperty) {
		//self.contentOfCurrentMailProperty=string;
        // If the current element is one whose content we care about, append 'string'
        // to the property that holds the content of the current element.
        [self.contentOfCurrentMailProperty appendString:string];
    }
}

- (void)addToMailList:(Mail *)newMail
{
	
}

@end
